<% if @project %>
  <%= render 'projects/header', project: @project, tab: 'kubernetes' %>
<% else %>
  <%= page_title "Kubernetes Resources" %>

  <%= search_form do %>
    <% projects = Project.where(id: Kubernetes::DeployGroupRole.pluck(Arel.sql('distinct project_id'))).order(:name).pluck(:name, :id) %>
    <%= search_select :project_id, projects, live: true, size: 3 %>

    <% deploy_groups = DeployGroup.where(id: Kubernetes::DeployGroupRole.pluck(Arel.sql('distinct deploy_group_id'))).sort_by(&:natural_order).map { |dg| [dg.name, dg.id] } %>
    <%= search_select :deploy_group_id, deploy_groups, live: true, size: 3 %>
  <% end %>

  <br/>
<% end %>

<section class="tabs kubernetes-section clearfix">
  <%= render 'samson_kubernetes/role_navigation' if @project %>

  <div class="table table-hover table-condensed">
    <table class="table">
      <tr>
        <% unless @project %>
          <th>Project</th>
        <% end %>
        <th>Deploy Group</th>
        <th>Role</th>
        <th>CPU<%= additional_info "Requested to Limit" %></th>
        <th>Memory<%= additional_info "Requested to Limit in MB" %></th>
        <th>Replicas</th>
        <th>Actions</th>
      </tr>

      <% @deploy_group_roles.each do |deploy_group_role| %>
        <tr>
          <% unless @project %>
            <td><%= link_to deploy_group_role.project.name, deploy_group_role.project %></td>
          <% end %>
          <td><%= DeployGroup.with_deleted { link_to deploy_group_role.deploy_group.name, deploy_group_role.deploy_group } %></td>
          <td><%= link_to deploy_group_role.kubernetes_role.name, [deploy_group_role.project, deploy_group_role.kubernetes_role] %></td>
          <td><%= deploy_group_role.requests_cpu %> to <%= deploy_group_role.limits_cpu %></td>
          <td><%= deploy_group_role.requests_memory %> to <%= deploy_group_role.limits_memory %></td>
          <td><%= deploy_group_role.replicas %></td>
          <td>
            <% if current_user.admin_for?(deploy_group_role.project) %>
              <%= link_to 'Edit', edit_kubernetes_deploy_group_role_path(deploy_group_role) %>
            <% end %>
          </td>
        </tr>
      <% end %>

      <tr>
        <td colspan="<%= @project ? 2 : 3 %>">Total</td>
        <td><%= @deploy_group_roles.sum { |d| d.requests_cpu * d.replicas } %> to <%= @deploy_group_roles.sum { |d| d.limits_cpu * d.replicas } %></td>
        <td><%= @deploy_group_roles.sum { |d| d.requests_memory * d.replicas } %> to <%= @deploy_group_roles.sum { |d| d.limits_memory * d.replicas } %></td>
        <td><%= @deploy_group_roles.sum(&:replicas) %></td>
        <td><%= link_to "Edit all", edit_many_project_kubernetes_deploy_group_roles_path(@project) if @project && current_user.admin_for?(@project) %></td>
      </tr>
    </table>
  </div>

  <div class="admin-actions">
    <div class="pull-right">
      <%= link_to "New", new_kubernetes_deploy_group_role_path, class: "btn btn-default" %>
    </div>
  </div>
</section>
